#include "jpanelmanager.h"
#include "inputmethod/jpanelfactory.h"

#include <QStackedWidget>
#include <QPointer>

namespace QTE
{

static Language gLanguage  = LGG_GeneralEnglish;

static QHash<Language, QPointer<JAbstractCandidatePanel>> gCandidatePanelHash;
static QHash<Language, QPointer<JAbstractInputPanel>> gSymbolPanelHash;
static QHash<Language, QPointer<JAbstractInputPanel>> gInputPanelHash;

JPanelManager::JPanelManager(QObject *parent) :
	QObject(parent)
{
	for(int i=LGG_GeneralEnglish; i<LGG_SimplifiedChinese; i++)
	{
		auto e = J_SCT(Language, i);
		gCandidatePanelHash.insert(e, JPanelFactory::createCandidatePanel(e));
		gSymbolPanelHash.insert(e, JPanelFactory::createSymbolPanel(e));
		gInputPanelHash.insert(e, JPanelFactory::createInputPanel(e));
	}
}

JPanelManager::~JPanelManager()
{

}

QString JPanelManager::defaultChangeLanguage()
{
	if( gLanguage == LGG_GeneralEnglish )
		return setCurrentLanguage(LGG_SimplifiedChinese);
	return setCurrentLanguage(LGG_GeneralEnglish);
}

QString JPanelManager::setCurrentLanguage(Language language)
{
	if( gLanguage == language )
		return inputMethodAbbreviation(gLanguage);

	candidatePanel()->hide();
	gLanguage = language;

	emit languageChanged(this);
	return inputMethodAbbreviation(gLanguage);
}

Language JPanelManager::currentLanguage() const
{
	return gLanguage;
}

#define _PANEL(panelHash, createMethod) \
({ \
	auto it = panelHash.find(gLanguage); \
	if( it == panelHash.end() ) \
		it = panelHash.insert(gLanguage, JPanelFactory::createMethod(gLanguage)); \
	else if( it->isNull() ) \
		*it = JPanelFactory::createMethod(gLanguage); \
	it->data(); \
})

JAbstractCandidatePanel *JPanelManager::candidatePanel() const
{
	return _PANEL(gCandidatePanelHash, createCandidatePanel);
}

JAbstractInputPanel *JPanelManager::symbolPanel() const
{
	return _PANEL(gSymbolPanelHash, createSymbolPanel);
}

JAbstractInputPanel *JPanelManager::inputPanel() const
{
	return _PANEL(gInputPanelHash, createInputPanel);
}

QString JPanelManager::panelName() const
{
	return inputMethodName(gLanguage);
}

QString JPanelManager::fullStopText() const
{
	switch(gLanguage)
	{
		case LGG_GeneralEnglish:    return ",";
		case LGG_SimplifiedChinese: return "，";
		default: break;
	}
	return "□";
}

QString JPanelManager::commaText() const
{
	switch(gLanguage)
	{
		case LGG_GeneralEnglish:    return ".";
		case LGG_SimplifiedChinese: return "。";
		default: break;
	}
	return "□";
}

} //namespace QTE
